package ast2

import (
	"strconv"

	"gitee.com/u-language/u-language/ucom/internal/errutil"
)

// sum 判断一个表达式是不是编译期常量表达式
// 如果是，且表达整数，计算出值
func sum(expr Expr, sbt *Sbt) (string, bool) {
	switch v := expr.(type) {
	case *Object:
		if v.Kind == INTOBJ {
			return v.Name, true
		} else if v.Kind == SymbolObj {
			n, _ := sbt.have(v.Name)
			if c, ok := n.(*ConstNode); ok {
				return sum(c.Value, sbt)
			}
		}
		return "", false
	case *OpExpr:
		src1, ok := sum(v.Src1, sbt)
		if !ok {
			return "", false
		}
		src2, ok := sum(v.Src2, sbt)
		if !ok {
			return "", false
		}
		src1I, err := strconv.ParseInt(src1, 10, 64)
		if err != nil {
			panic(errutil.NewErr2(errutil.CompileErr, err.Error()))
		}
		src2I, err := strconv.ParseInt(src2, 10, 64)
		if err != nil {
			panic(errutil.NewErr2(errutil.CompileErr, err.Error()))
		}
		ret := strconv.Itoa(int(src1I) + int(src2I))
		return ret, true
	}
	return "", false
}
